import classNames from 'classnames';
import styles from './index.module.scss';
import { useRef, useEffect } from 'react';
// 1,定义props类型
interface textareaProps
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  value: string;
}
export default function Textarea(props: textareaProps) {
  //2.1声明ref
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  //2,实现最大的长度限制 默认值是100
  const {
    maxLength = 100,
    className,
    value,
    autoFocus = true,
    ...restProps
  } = props;

  //2.3 生命周期挂载后触发 光标选中
  //https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/setSelectionRange 控制光标出现的位置光标在
  useEffect(() => {
    textareaRef.current?.setSelectionRange(-1, -1);
  }, []);

  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        //2.2 绑定ref
        ref={textareaRef}
        className={classNames('textarea', className)}
        {...restProps}
        maxLength={maxLength}
        //4, 统计当前字数
        value={value}
        autoFocus={autoFocus}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {value.length}/{maxLength}
      </div>
    </div>
  );
}
